'use strict';
const requireEx =require('yi-require');
module.exports = requireEx('yi-restful').c('bgm',[]);
const ObjectId = require('mongodb').ObjectID;
const lookup = require('yi-lookup');

const beforeSend = function (req,body,callback) {
    let userList = body.data.items;

    let lookupList = [];
    lookupList.push({
        from:"user",
        localField:"userId",
        foreignField:"_id",
        project:{createTime:0,lastModifyDate:0,pwd:0}
    }) ;

    lookup.lookup(req.mongo,userList,lookupList,(e,r)=> {
        userList=[];
        r.forEach((item)=>{
            userList.push(item.userId);
        });
        callback(null, body);
    });
};


const middleware =  (req, res, next) =>{
    let authInfo =  req.context||req.context.authInfo ;
    if(!req.context || !req.context.authInfo){
        return res.err.unauthorized();
    }
    authInfo = authInfo.authInfo;

    req.beforeSend = beforeSend;
    next();
};

const handler =  (req, res, next) =>{
    if(!(req.body.followedUserId||req.body.followedMallId||req.body.followedStoreId)){
        return res.reply({code:60002,message:"没有关注对象！"});
    }

    if(req.body.isFollow===-1){
        delete req.body.isFollow;
    }
    req.query = req.query||{};
    if(req.query.page){
        req.query.page={
            size:10,
            index:1
        };
    }

    let q = req.mongo.collection('fans').find(req.query.filter).project({_id:0,userId:1});
    q.count(function (err, count) {
        if (err) return res.err.mongoError(err);

        page.count = count;
        page.pageCount = Math.ceil(page.count / page.size);
        if(count<=0) return res.reply({code:0,message:"查询成功",data:page});
        page.hasPrevious = page.index > 1;
        page.hasNext = page.index < page.pageCount;

        //请求页大于最大页码，即请求最大页码
        page.index = page.pageCount < page.index ? page.pageCount : page.index;
        let skip = page.size * (page.index - 1);
        let limit = page.size;

        q.skip(skip).limit(limit).toArray(function (err, list) {
            if (err) return res.err.mongoError(err);
            page.items = list;

            // res.reply(page);
            res.reply({code:0,message:"查询成功",data:page});
        });
    });
};

module.exports = {
    open:false,
    description:'获取关注列表',
    middleware:middleware,
    handler: handler
};
